﻿using System;
using UnityEngine;
using XLua;

[CSharpCallLua]
public delegate void LuaPushEvent(string eventStr, object param);

public class LuaObjectMgr : MonoBehaviour
{
    private Action mAwakeFunc;
    private Action mUpdateFunc;
    private Action mDestroyFunc;

    private LuaTable mLuaTable;
    private LuaPushEvent mPushEvent;
    
    void Awake()
    {
        // 提前加载对应的文件
        mLuaTable = LuaMgr.GetSingleton().GetLuaTable("LuaObjectMgr");
        if (mLuaTable == null) { return; }
        mPushEvent = mLuaTable.Get<LuaPushEvent>("PushLuaEvent");

        // 获取对应的Lua函数接口
        mAwakeFunc = mLuaTable.Get<Action>("Awake");
        mUpdateFunc = mLuaTable.Get<Action>("Update");
        mDestroyFunc = mLuaTable.Get<Action>("Destroy");
        
        if (mAwakeFunc != null)
        {
            mAwakeFunc();
        }
    }

    void Update()
    {
        if (mUpdateFunc != null)
        {
            mUpdateFunc();
        }
    }

    void OnDestroy()
    {
        if (mDestroyFunc != null)
        {
            mDestroyFunc();
        }

        // 销毁Lua接口函数
        mAwakeFunc = null;
        mUpdateFunc = null;
        mDestroyFunc = null;

        // 销毁对应的Table（一定要执行啊，否则内存泄露）
        if (mLuaTable != null)
        {
            mLuaTable.Dispose();
        }
        mLuaTable = null;
        mPushEvent = null;
    }
    
    public void PushLuaEvent(string eventStr, object param = null)
    {
        if (mPushEvent != null)
        {
            mPushEvent(eventStr, param);
        }
    }
}